/*******************************************************
> Copyright (C) 2024 ==IOT== All rights reserved.
> File Name: device.c
> Author: sy
> Website:www.sy.org
> Created Time: 2024年09月23日 星期一 11时30分45秒
***************************************************/

#include "device.h"

void input_cjson_dev(struct device_function dev, char *dest);

int main(int argc, const char *argv[])
{
    int sock = 0;
    int ret = 0;
    char dest[1024] = {0};

    struct device_function dev;
    memset(&dev, 0, sizeof(dev));

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = inet_addr(IP);

    // 创建socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 连接
    ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
    if (ret == -1)
    {
        perror("connect");
        close(sock); // 关闭socket
        exit(EXIT_FAILURE);
    }

    // 初始化随机数种子
    srand(time(NULL));

    while (1)
    {
        // 随机生成设备数据
        dev.water_level = rand() % 20;//水位
        dev.flow_rate = rand() % 20;//流量
        dev.motor_temperature = rand() % 300;//电机温度
        time_t rawtime = time(NULL);
        struct tm *timeinfo = localtime(&rawtime);

        // 更新时间字符串
        sprintf(dev.time, "%04d-%02d-%02d %02d:%02d:%02d",
                timeinfo->tm_year + 1900,
                timeinfo->tm_mon + 1,
                timeinfo->tm_mday,
                timeinfo->tm_hour,
                timeinfo->tm_min,
                timeinfo->tm_sec);

        strcpy(dev.type, "dev");
        strcpy(dev.gate_valve_condition, "on");

        // 序列化设备数据为JSON
        input_cjson_dev(dev, dest);
        ret = send(sock, dest, strlen(dest), 0);
        if (ret == -1)
        {
            perror("send");
            close(sock); // 关闭socket
            exit(EXIT_FAILURE);
        }

        sleep(1);
    }

    close(sock); // 关闭socket
    return 0;
}

void input_cjson_dev(struct device_function dev, char *dest)
{
    cJSON *json = cJSON_CreateObject();
    if (!json)
    {
        fprintf(stderr, "Failed to create JSON object\n");
        return;
    }

    cJSON_AddItemToObject(json, "type", cJSON_CreateString(dev.type));
    cJSON_AddItemToObject(json, "time", cJSON_CreateString(dev.time));
    cJSON_AddItemToObject(json, "water_level", cJSON_CreateNumber(dev.water_level));
    cJSON_AddItemToObject(json, "flow_rate", cJSON_CreateNumber(dev.flow_rate));
    cJSON_AddItemToObject(json, "motor_temperature", cJSON_CreateNumber(dev.motor_temperature));
    cJSON_AddItemToObject(json, "gate_valve_condition", cJSON_CreateString(dev.gate_valve_condition));
    
    char *jsonStr = cJSON_Print(json);
    if (jsonStr)
    {
        strcpy(dest, jsonStr);
        free(jsonStr); // 注意释放分配的内存
    }
    else
    {
        fprintf(stderr, "Failed to print JSON\n");
    }

    cJSON_Delete(json);
}
